<template>
  <div class="team-member-container">
    <a-card :title="`团队成员管理 - ${spaceName}`" :bordered="false">
      <template #extra>
        <a-button type="link" @click="handleBack">返回空间列表</a-button>
      </template>

      <!-- 顶部操作区域 -->
      <div class="header-actions">
        <a-space>
          <a-button type="primary" @click="handleAddMember">
            <template #icon><UserAddOutlined /></template>
            添加成员
          </a-button>
          <a-button @click="fetchMemberList">
            <template #icon><ReloadOutlined /></template>
            刷新
          </a-button>
        </a-space>
      </div>

      <!-- 成员列表 -->
      <a-table
        :columns="columns"
        :data-source="memberList"
        :loading="loading"
        :pagination="false"
        row-key="id"
        :locale="{ emptyText: '暂无团队成员' }"
      >
        <!-- 用户信息 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'user'">
            <div class="user-info">
              <a-avatar :src="record.userVO?.userAvatar" size="large">
                {{ record.userVO?.userName?.charAt(0) }}
              </a-avatar>
              <div class="user-details">
                <div class="user-name">{{ record.userVO?.userName }}</div>
                <div class="user-account">{{ record.userVO?.userAccount }}</div>
              </div>
            </div>
          </template>

          <!-- 角色标签 -->
          <template v-else-if="column.key === 'spaceRole'">
            <a-tag :color="getSpaceRoleColor(record.spaceRole)">
              {{ getSpaceRoleText(record.spaceRole) }}
            </a-tag>
            <div class="role-description">{{ getSpaceRoleDescription(record.spaceRole) }}</div>
          </template>

          <!-- 加入时间 -->
          <template v-else-if="column.key === 'createTime'">
            {{ formatDateTime(record.createTime) }}
          </template>

          <!-- 操作按钮 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEditMember(record)">
                <template #icon><EditOutlined /></template>
                编辑角色
              </a-button>
              <a-popconfirm
                title="确定要移除该成员吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDeleteMember(record)"
              >
                <a-button type="link" size="small" danger>
                  <template #icon><DeleteOutlined /></template>
                  移除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加成员弹窗 -->
    <a-modal
      v-model:open="addModalVisible"
      title="添加团队成员"
      @ok="handleConfirmAdd"
      @cancel="handleCancelAdd"
      :confirm-loading="addLoading"
    >
      <a-form ref="addFormRef" :model="addForm" :rules="addRules" layout="vertical">
        <a-form-item label="用户ID" name="userId">
          <a-input v-model:value="addForm.userId" placeholder="请输入用户ID" style="width: 100%" />
          <div class="form-tip">请输入要添加的用户ID（长整型ID，请勿转换为数字）</div>
        </a-form-item>
        <a-form-item label="角色权限" name="spaceRole">
          <a-radio-group v-model:value="addForm.spaceRole">
            <a-radio
              v-for="option in SPACE_ROLE_OPTIONS"
              :key="option.value"
              :value="option.value"
              style="display: block; margin-bottom: 12px"
            >
              <div class="role-option">
                <div class="role-name">{{ option.label }}</div>
                <div class="role-desc">{{ option.description }}</div>
              </div>
            </a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑角色弹窗 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑成员角色"
      @ok="handleConfirmEdit"
      @cancel="handleCancelEdit"
      :confirm-loading="editLoading"
    >
      <a-form ref="editFormRef" :model="editForm" :rules="editRules" layout="vertical">
        <a-form-item label="角色权限" name="spaceRole">
          <a-radio-group v-model:value="editForm.spaceRole">
            <a-radio
              v-for="option in SPACE_ROLE_OPTIONS"
              :key="option.value"
              :value="option.value"
              style="display: block; margin-bottom: 12px"
            >
              <div class="role-option">
                <div class="role-name">{{ option.label }}</div>
                <div class="role-desc">{{ option.description }}</div>
              </div>
            </a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  UserAddOutlined,
  ReloadOutlined,
  EditOutlined,
  DeleteOutlined,
} from '@ant-design/icons-vue'
import { listSpaceUser, addSpaceUser, editSpaceUser, deleteSpaceUser } from '@/api/space-user'
import type { SpaceUserVO, SpaceUserAddRequest, SpaceUserEditRequest } from '@/types/space-user'
import {
  SPACE_ROLE_OPTIONS,
  getSpaceRoleText,
  getSpaceRoleColor,
  getSpaceRoleDescription,
} from '@/types/space-user'
import type { FormInstance } from 'ant-design-vue'

const router = useRouter()
const route = useRoute()

// 路由参数
const spaceId = ref<string>(String(route.params.spaceId))
const spaceName = ref<string>(String(route.query.spaceName || '团队空间'))

// 响应式数据
const loading = ref(false)
const addLoading = ref(false)
const editLoading = ref(false)
const memberList = ref<SpaceUserVO[]>([])
const addModalVisible = ref(false)
const editModalVisible = ref(false)
const addFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()

// 添加成员表单
const addForm = reactive<SpaceUserAddRequest>({
  spaceId: spaceId.value,
  userId: '',
  spaceRole: 'viewer',
})

// 编辑角色表单
const editForm = reactive<SpaceUserEditRequest>({
  id: '',
  spaceRole: 'viewer',
})

// 表单验证规则
const addRules = {
  userId: [
    { required: true, message: '请输入用户ID' },
    { type: 'string', message: '请输入有效的用户ID' },
  ],
  spaceRole: [{ required: true, message: '请选择角色权限' }],
}

const editRules = {
  spaceRole: [{ required: true, message: '请选择角色权限' }],
}

// 表格列配置
const columns = [
  {
    title: '成员信息',
    key: 'user',
    width: 250,
  },
  {
    title: '角色权限',
    key: 'spaceRole',
    width: 200,
  },
  {
    title: '加入时间',
    key: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
]

// 获取成员列表
const fetchMemberList = async () => {
  try {
    loading.value = true
    const response = await listSpaceUser({ spaceId: spaceId.value })

    // 处理不同的响应结构
    if (response.data.data) {
      memberList.value = response.data.data
    } else if (Array.isArray(response.data)) {
      // 如果 response.data 本身就是数组
      memberList.value = response.data
    } else {
      memberList.value = []
    }
  } catch (error: unknown) {
    console.error('获取成员列表失败:', error)
    message.error('获取成员列表失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// 返回空间列表
const handleBack = () => {
  router.push({ name: 'SpaceList' })
}

// 添加成员
const handleAddMember = () => {
  addForm.spaceId = spaceId.value
  addForm.userId = ''
  addForm.spaceRole = 'viewer'
  addModalVisible.value = true
}

// 确认添加
const handleConfirmAdd = () => {
  addFormRef.value
    ?.validateFields()
    .then(async () => {
      try {
        addLoading.value = true
        await addSpaceUser(addForm)
        message.success('添加成员成功')
        addModalVisible.value = false
        fetchMemberList()
      } catch (error: unknown) {
        console.error('添加成员失败:', error)
        message.error('添加成员失败')
      } finally {
        addLoading.value = false
      }
    })
    .catch(() => {
      // 验证失败，不做任何处理
    })
}

// 取消添加
const handleCancelAdd = () => {
  addModalVisible.value = false
  addFormRef.value?.resetFields()
}

// 编辑成员角色
const handleEditMember = (member: SpaceUserVO) => {
  editForm.id = member.id
  editForm.spaceRole = member.spaceRole
  editModalVisible.value = true
}

// 确认编辑
const handleConfirmEdit = () => {
  editFormRef.value
    ?.validateFields()
    .then(async () => {
      try {
        editLoading.value = true
        await editSpaceUser(editForm)
        message.success('修改角色成功')
        editModalVisible.value = false
        fetchMemberList()
      } catch (error: unknown) {
        console.error('修改角色失败:', error)
        message.error('修改角色失败')
      } finally {
        editLoading.value = false
      }
    })
    .catch(() => {
      // 验证失败，不做任何处理
    })
}

// 取消编辑
const handleCancelEdit = () => {
  editModalVisible.value = false
  editFormRef.value?.resetFields()
}

// 删除成员
const handleDeleteMember = async (member: SpaceUserVO) => {
  try {
    await deleteSpaceUser({ id: member.id })
    message.success('移除成员成功')
    fetchMemberList()
  } catch (error: unknown) {
    console.error('移除成员失败:', error)
    message.error('移除成员失败')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchMemberList()
})
</script>

<style scoped>
.team-member-container {
  padding: 24px;
}

.header-actions {
  margin-bottom: 24px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 500;
  font-size: 14px;
  color: #262626;
}

.user-account {
  font-size: 12px;
  color: #8c8c8c;
}

.role-description {
  font-size: 12px;
  color: #8c8c8c;
  margin-top: 4px;
}

.form-tip {
  font-size: 12px;
  color: #8c8c8c;
  margin-top: 4px;
}

.role-option {
  display: flex;
  flex-direction: column;
}

.role-name {
  font-weight: 500;
  color: #262626;
}

.role-desc {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

:deep(.ant-radio-wrapper) {
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  transition: all 0.3s;
}

:deep(.ant-radio-wrapper:hover) {
  border-color: #1890ff;
}

:deep(.ant-radio-wrapper-checked) {
  border-color: #1890ff;
  background: #f6ffed;
}
</style>
